import { Footer } from '@/components';
import { userRegisterUsingPost } from '@/services/pikimbi/userController';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Helmet, history } from '@umijs/max';
import { Alert, App, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});
const Register: React.FC = () => {
  const [userRegisterState, setUserRegisterState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { styles } = useStyles();
  const { message } = App.useApp(); // 获取消息实例

  const handleSubmit = async (values: API.UserLoginRequest) => {
    try {
      const res = await userRegisterUsingPost(values);
      if (res.code === 0) {
        message.success('注册成功！');
        history.push('./login');
      } else {
        const errorMsg = res.message || '注册失败，请重试';
        message.error(errorMsg);
        setUserRegisterState(res);
      }
    } catch (error) {
      // 根据实际错误类型细化提示（例如网络错误、服务端异常等）
      const errorMsg = error.message || '请求失败，请检查网络连接';
      message.error(errorMsg);
      console.error('注册异常:', error);
      // 可选：更新状态或记录错误日志
      setUserRegisterState({ code: -1, message: errorMsg });
    }
  };

  const { status, type: loginType } = userRegisterState;

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'注册页面'} - {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="pikim 智能BI"
          subTitle="pipkim 智能BI，支持图文智能分析的BI项目"
          onFinish={async (values) => {
            await handleSubmit(values as API.UserLoginRequest);
          }}
          submitter={{
            searchConfig: {
              submitText: '注册', // 将按钮文本改为“注册”
            },
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '用户注册',
              },
            ]}
          />

          {status === 'error' && loginType === 'account' && (
            <Alert style={{ marginBottom: 24 }} message="账户或密码错误" type="error" showIcon />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="确认密码"
                rules={[
                  {
                    required: true,
                    message: '请确认密码！',
                  },
                ]}
              />
            </>
          )}
          <div style={{ marginBottom: 24 }}>
            <a href={'/user/login'}>返回登录</a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Register;
